package algorithm.unionfind;

public class UnionFindRankCompression extends AbstractUnionFind {


    private int[] rank;

    public UnionFindRankCompression(int capacity) {
        super(capacity);
        rank = new int[capacity];
        for (int i = 0; i < capacity; i++) {
            rank[i] = 1;
        }
    }


    @Override
    public int find(int p) {
        while (p != data[p]) {
            data[p] = data[data[p]];
            p = data[p];
        }

//        if (p!=data[p]){
//            data[p] = find(data[p]);
//        }
        return p;
    }



    @Override
    public void union(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);

        if (pRoot == qRoot) {
            return;
        }
        //判断哪个size，则以哪个为主
        if (rank[pRoot]<rank[qRoot]){
            data[pRoot] = qRoot;
        }else if (rank[pRoot]>rank[qRoot]){
            data[pRoot] = qRoot;
        }else{
            data[pRoot] = qRoot;
            data[qRoot]++;
        }
    }
}
